package com.github.shiqiyue.learn.curator.recipe;

import com.github.shiqiyue.learn.curator.ClientUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/***
 * 分布式锁-测试
 * @author wenyao.wu
 * @date 2019/1/21
 */
public class LockTest {

    private static final Logger logger = LoggerFactory.getLogger(LockTest.class);


    public static void main(String[] args) throws Exception {
        CuratorFramework client = ClientUtil.getClient(null);
        String lockPath = "/lock2";
        Integer maxWait = 10;
        TimeUnit waitUnit = TimeUnit.SECONDS;

        InterProcessMutex lock = new InterProcessMutex(client, lockPath);
        if (lock.acquire(maxWait, waitUnit)) {
            try {
                logger.info("获得锁");
                logger.info("开始运算");
                Thread.sleep(5000);
                logger.info("结束运算");
            } finally {
                logger.info("释放锁");
                lock.release();
            }
        }
        client.close();
    }
}
